#include "./ctp/ThostFtdcTraderApi.h"
#include "./ctp/ThostFtdcUserApiStruct.h"
#include "tradehandler.h"
#include <unistd.h>
#include <cstring>
#include "logger.h"
#include "gbk_utf8.h"
#include <iostream>
#include <iomanip>

int nRequestID = static_cast<int>(time(nullptr));
// std::string ORD = "";


CTraderHandler::CTraderHandler(const std::string& brokerID, const std::string& userID, const std::string& password, const std::string& flow_path, const std::string& front_address, const std::string& app_id, const std::string& auth_code, TcpServer* tcp_server):
    m_brokerID(brokerID), m_userID(userID), m_password(password), m_flow_path(flow_path), m_front_address(front_address), m_app_id(app_id), m_auth_code(auth_code), m_tcp_server(tcp_server) {
    if (brokerID.empty() || userID.empty() || password.empty() || flow_path.empty() || front_address.empty()) {
        throw std::invalid_argument("必须提供 BrokerID、UserID、Password、flow_path 和 front_address");
    }
    
    if (tcp_server == nullptr) {
        Logger::warn("TCP服务器指针为空，部分功能可能无法使用");
    }
}
    
void CTraderHandler::connect()
{
    Logger::info("开始连接交易接口...");
    m_ptraderapi = CThostFtdcTraderApi::CreateFtdcTraderApi(m_flow_path.c_str());
    
    if (!m_ptraderapi) {
        Logger::error("创建交易API实例失败!");
        return;
    }
    
    Logger::info("交易API实例创建成功，地址: " + std::to_string((intptr_t)m_ptraderapi));
    
    m_ptraderapi->RegisterSpi(this);
    m_ptraderapi->SubscribePublicTopic(THOST_TERT_QUICK);
    m_ptraderapi->SubscribePrivateTopic(THOST_TERT_QUICK);
    
    char* front_address = const_cast<char*>(m_front_address.c_str());
    m_ptraderapi->RegisterFront(front_address);
    
    Logger::info("初始化交易API...");
    m_ptraderapi->Init();
    Logger::info("API版本: " + std::string(m_ptraderapi->GetApiVersion()));
}

void CTraderHandler::release()
{
    m_ptraderapi->Release();
}

void CTraderHandler::login()
{
    Logger::info("开始登录交易接口...");
    CThostFtdcReqUserLoginField t = {0};
    strncpy(t.BrokerID, m_brokerID.c_str(), sizeof(t.BrokerID) - 1);
    t.BrokerID[sizeof(t.BrokerID) - 1] = '\0';
    strncpy(t.UserID, m_userID.c_str(), sizeof(t.UserID) - 1);
    t.UserID[sizeof(t.UserID) - 1] = '\0';
    strncpy(t.Password, m_password.c_str(), sizeof(t.Password) - 1);
    t.Password[sizeof(t.Password) - 1] = '\0';
    int r = m_ptraderapi->ReqUserLogin(&t, nRequestID++);
    if (r != 0) {
        Logger::error("login failed, error code: " + std::to_string(r));
    }
}

void CTraderHandler::settlementinfoConfirm()
{
    Logger::info("开始结算单确认...");
    CThostFtdcSettlementInfoConfirmField t = {0};
    strncpy(t.BrokerID, m_brokerID.c_str(), sizeof(t.BrokerID) - 1);
    t.BrokerID[sizeof(t.BrokerID) - 1] = '\0';
    strncpy(t.InvestorID, m_userID.c_str(), sizeof(t.InvestorID) - 1);
    t.InvestorID[sizeof(t.InvestorID) - 1] = '\0';
    int r = m_ptraderapi->ReqSettlementInfoConfirm(&t, nRequestID++);
    if (r != 0) {
        Logger::error("settlementinfoConfirm failed, error code: " + std::to_string(r));
    }
}

int CTraderHandler::orderInsert(
    const std::string& instrument,
    const std::string& exchange,
    const std::string& direction,
    const double price,
    const int volume,
    const std::string& offect,
    const std::string& order_ref)
{
    if (!isReady()) {
        Logger::error("交易接口未就绪，请检查连接状态");
        return -1;
    }

    if (instrument.empty() || exchange.empty() || direction.empty()) {
        Logger::error("订单参数不完整");
        return -3;
    }

    if (price <= 0 || volume <= 0) {
        Logger::error("价格或数量必须大于0");
        return -4;
    }

    CThostFtdcInputOrderField ord = {0};
    
    Logger::info("orderInsert");
    
    strncpy(ord.BrokerID, m_brokerID.c_str(), sizeof(ord.BrokerID)-1);
    ord.BrokerID[sizeof(ord.BrokerID)-1] = '\0';
    Logger::debug("BrokerID设置为: " + std::string(ord.BrokerID));

    strncpy(ord.InvestorID, m_userID.c_str(), sizeof(ord.InvestorID)-1);
    ord.InvestorID[sizeof(ord.InvestorID)-1] = '\0';
    Logger::debug("InvestorID设置为: " + std::string(ord.InvestorID));

    strncpy(ord.InstrumentID, instrument.c_str(), sizeof(ord.InstrumentID)-1);
    ord.InstrumentID[sizeof(ord.InstrumentID)-1] = '\0';
    Logger::debug("InstrumentID设置为: " + std::string(ord.InstrumentID));

    strncpy(ord.ExchangeID, exchange.c_str(), sizeof(ord.ExchangeID)-1);
    ord.ExchangeID[sizeof(ord.ExchangeID)-1] = '\0';
    Logger::debug("ExchangeID设置为: " + std::string(ord.ExchangeID));
    
    ord.LimitPrice = price;
    ord.VolumeTotalOriginal = volume;
    Logger::debug("价格设置为: " + std::to_string(ord.LimitPrice));
    Logger::debug("数量设置为: " + std::to_string(ord.VolumeTotalOriginal));
    
    ord.OrderPriceType = THOST_FTDC_OPT_LimitPrice;
    ord.Direction = direction == "buy" ? THOST_FTDC_D_Buy : THOST_FTDC_D_Sell;
    ord.CombOffsetFlag[0] = (offect == "close") ? THOST_FTDC_OF_Close :
                            (offect == "close_today") ? THOST_FTDC_OF_CloseToday :
                            THOST_FTDC_OF_Open;
    ord.CombHedgeFlag[0] = THOST_FTDC_HF_Speculation;
    ord.TimeCondition = THOST_FTDC_TC_GFD;
    ord.VolumeCondition = THOST_FTDC_VC_AV;
    ord.MinVolume = 1;
    ord.ContingentCondition = THOST_FTDC_CC_Immediately;
    ord.StopPrice = 0;
    ord.ForceCloseReason = THOST_FTDC_FCC_NotForceClose;
    ord.IsAutoSuspend = 0;
    strncpy(ord.OrderRef, order_ref.c_str(), sizeof(ord.OrderRef)-1);
    ord.OrderRef[sizeof(ord.OrderRef)-1] = '\0';
    Logger::debug("OrderRef设置为: " + std::string(ord.OrderRef));

    Logger::debug("准备发送订单...");
    Logger::debug("m_ptraderapi地址: " + std::to_string((intptr_t)m_ptraderapi));
    
    try {
        int requestID = nRequestID++;
        Logger::debug("使用请求ID: " + std::to_string(requestID));
        int result = m_ptraderapi->ReqOrderInsert(&ord, requestID);
        Logger::debug("下单结果: " + std::to_string(result));
        return result;
    } catch (const std::exception& e) {
        Logger::error("发送订单时发生异常: " + std::string(e.what()));
        return -2;
    }
}

int CTraderHandler::orderCancel(const std::string& instrument, const std::string& exchange, const std::string& sid)
{
    CThostFtdcInputOrderActionField ord = {0};
    Logger::info("orderCancel: " + instrument + ", " + exchange + ", " + sid);
    strncpy(ord.BrokerID, m_brokerID.c_str(), sizeof(ord.BrokerID) - 1);
    ord.BrokerID[sizeof(ord.BrokerID) - 1] = '\0';
    strncpy(ord.InvestorID, m_userID.c_str(), sizeof(ord.InvestorID) - 1);
    ord.InvestorID[sizeof(ord.InvestorID) - 1] = '\0';
    strncpy(ord.ExchangeID, exchange.c_str(), sizeof(ord.ExchangeID) - 1);
    ord.ExchangeID[sizeof(ord.ExchangeID) - 1] = '\0';
    strncpy(ord.InstrumentID, instrument.c_str(), sizeof(ord.InstrumentID) - 1);
    ord.InstrumentID[sizeof(ord.InstrumentID) - 1] = '\0';
    strncpy(ord.UserID, m_userID.c_str(), sizeof(ord.UserID) - 1);
    ord.UserID[sizeof(ord.UserID) - 1] = '\0';
    strncpy(ord.OrderSysID, sid.c_str(), sizeof(ord.OrderSysID) - 1);
    ord.OrderSysID[sizeof(ord.OrderSysID) - 1] = '\0';

    // 添加调试输出
    // std::cout << "OrderSysID 二进制内容:" << std::endl;
    // for(size_t i = 0; i < sizeof(ord.OrderSysID); i++) {
    //     std::cout << std::hex << std::setw(2) << std::setfill('0') 
    //               << static_cast<int>(static_cast<unsigned char>(ord.OrderSysID[i])) << " ";
    // }
    // std::cout << std::endl;
    
    // std::cout << "OrderSysID 字符内容: '" << ord.OrderSysID << "'" << std::endl;
    // std::cout << "OrderSysID 长度: " << strlen(ord.OrderSysID) << std::endl;

    ord.ActionFlag = THOST_FTDC_AF_Delete;
    return m_ptraderapi->ReqOrderAction(&ord, nRequestID++);
}

void CTraderHandler::qryInstrument(const std::string& exchange)
{
    CThostFtdcQryInstrumentField t = {0};
    if (!exchange.empty()) {
        strncpy(t.ExchangeID, exchange.c_str(), sizeof(t.ExchangeID) - 1);
        t.ExchangeID[sizeof(t.ExchangeID) - 1] = '\0';
    }
    if (m_ptraderapi->ReqQryInstrument(&t, nRequestID++) != 0)
        Logger::error("qry instrument failed! " + exchange);
    else
        Logger::info("qry instrument success! " + exchange);
}

int CTraderHandler::getOrder(const std::string& exchange)
{
    Logger::info("getOrder: " + exchange);
    CThostFtdcQryOrderField a = {0};
    strncpy(a.BrokerID, m_brokerID.c_str(), sizeof(a.BrokerID) - 1);
    a.BrokerID[sizeof(a.BrokerID) - 1] = '\0';
    strncpy(a.InvestorID, m_userID.c_str(), sizeof(a.InvestorID) - 1);
    a.InvestorID[sizeof(a.InvestorID) - 1] = '\0';
    if (!exchange.empty()) {
        strncpy(a.ExchangeID, exchange.c_str(), sizeof(a.ExchangeID) - 1);
        a.ExchangeID[sizeof(a.ExchangeID) - 1] = '\0';
    }
    return m_ptraderapi->ReqQryOrder(&a, nRequestID++);
}

int CTraderHandler::getAccount()
{
    Logger::info("getAccount");
    CThostFtdcQryTradingAccountField a = {0};
    strncpy(a.BrokerID, m_brokerID.c_str(), sizeof(a.BrokerID) - 1);
    a.BrokerID[sizeof(a.BrokerID) - 1] = '\0';
    strncpy(a.InvestorID, m_userID.c_str(), sizeof(a.InvestorID) - 1);
    a.InvestorID[sizeof(a.InvestorID) - 1] = '\0';
    return m_ptraderapi->ReqQryTradingAccount(&a, nRequestID++);
}

int CTraderHandler::getPosition()
{
    Logger::info("getPosition");
    CThostFtdcQryInvestorPositionField a = {0};
    strncpy(a.BrokerID, m_brokerID.c_str(), sizeof(a.BrokerID) - 1);
    a.BrokerID[sizeof(a.BrokerID) - 1] = '\0';
    strncpy(a.InvestorID, m_userID.c_str(), sizeof(a.InvestorID) - 1);
    a.InvestorID[sizeof(a.InvestorID) - 1] = '\0';
    return m_ptraderapi->ReqQryInvestorPosition(&a, nRequestID++);
}

int CTraderHandler::getTrade()
{
    Logger::info("getTrade");
    CThostFtdcQryTradeField a = {0};
    strncpy(a.BrokerID, m_brokerID.c_str(), sizeof(a.BrokerID) - 1);
    a.BrokerID[sizeof(a.BrokerID) - 1] = '\0';
    strncpy(a.InvestorID, m_userID.c_str(), sizeof(a.InvestorID) - 1);
    a.InvestorID[sizeof(a.InvestorID) - 1] = '\0';
    return m_ptraderapi->ReqQryTrade(&a, nRequestID++);
};

// 回调函数实现
void CTraderHandler::OnFrontConnected()
{
    Logger::info("OnFrontConnected");
    m_connected = true;
    // login();
    ReqAuthenticate();
}

void CTraderHandler::OnFrontDisconnected(int nReason)
{
    Logger::info("OnFrontDisconnected");
    Logger::info("nReason: " + std::to_string(nReason));
    m_connected = false;
    sleep(1);  // 等待1秒后重新连接
    connect();
}

// 登陆请求响应
void CTraderHandler::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    Logger::info("OnRspUserLogin");
    if (!pRspInfo || pRspInfo->ErrorID == 0) {
        m_logged_in = true;
        Logger::info("登录成功");
    } else {
        Logger::error("登录失败");
    }
}

// 结算单确认响应
void CTraderHandler::OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    Logger::info("OnRspSettlementInfoConfirm");
    m_settlement_confirmed = true;
}

// 查询合约响应
void CTraderHandler::OnRspQryInstrument(CThostFtdcInstrumentField *pInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    if(m_tcp_server != nullptr) {
        try {
            json instrument_data;
            instrument_data["type"] = "instrument_data";
            
            if (pInstrument == nullptr) {
                instrument_data["data"] = nullptr;
            } else {
                instrument_data["data"]["InstrumentID"] = pInstrument->InstrumentID;
                instrument_data["data"]["ExchangeID"] = pInstrument->ExchangeID;
                instrument_data["data"]["InstrumentName"] = pInstrument->InstrumentName;
                instrument_data["data"]["ExchangeInstID"] = pInstrument->ExchangeInstID;
                instrument_data["data"]["ProductID"] = pInstrument->ProductID;
                instrument_data["data"]["ProductClass"] = std::string(1, pInstrument->ProductClass);
                instrument_data["data"]["DeliveryYear"] = pInstrument->DeliveryYear;
                instrument_data["data"]["DeliveryMonth"] = pInstrument->DeliveryMonth;
                instrument_data["data"]["MaxMarketOrderVolume"] = pInstrument->MaxMarketOrderVolume;
                instrument_data["data"]["MinMarketOrderVolume"] = pInstrument->MinMarketOrderVolume;
                instrument_data["data"]["MaxLimitOrderVolume"] = pInstrument->MaxLimitOrderVolume;
                instrument_data["data"]["MinLimitOrderVolume"] = pInstrument->MinLimitOrderVolume;
                instrument_data["data"]["VolumeMultiple"] = pInstrument->VolumeMultiple;
                instrument_data["data"]["PriceTick"] = pInstrument->PriceTick;
                instrument_data["data"]["CreateDate"] = pInstrument->CreateDate;
                instrument_data["data"]["OpenDate"] = pInstrument->OpenDate;
                instrument_data["data"]["ExpireDate"] = pInstrument->ExpireDate;
                instrument_data["data"]["StartDelivDate"] = pInstrument->StartDelivDate;
                instrument_data["data"]["EndDelivDate"] = pInstrument->EndDelivDate;
                instrument_data["data"]["InstLifePhase"] = std::string(1, pInstrument->InstLifePhase);
                instrument_data["data"]["IsTrading"] = pInstrument->IsTrading;
                instrument_data["data"]["PositionType"] = std::string(1, pInstrument->PositionType);
                instrument_data["data"]["PositionDateType"] = std::string(1, pInstrument->PositionDateType);
                instrument_data["data"]["LongMarginRatio"] = pInstrument->LongMarginRatio;
                instrument_data["data"]["ShortMarginRatio"] = pInstrument->ShortMarginRatio;
                instrument_data["data"]["MaxMarginSideAlgorithm"] = std::string(1, pInstrument->MaxMarginSideAlgorithm);
                instrument_data["data"]["UnderlyingInstrID"] = pInstrument->UnderlyingInstrID;
                instrument_data["data"]["StrikePrice"] = pInstrument->StrikePrice;
                instrument_data["data"]["OptionsType"] = std::string(1, pInstrument->OptionsType);
                instrument_data["data"]["UnderlyingMultiple"] = pInstrument->UnderlyingMultiple;
                instrument_data["data"]["CombinationType"] = std::string(1, pInstrument->CombinationType);
            }
            
            instrument_data["bIsLast"] = bIsLast;
            
            if (pRspInfo) {
                instrument_data["error"]["ErrorID"] = pRspInfo->ErrorID;
                instrument_data["error"]["ErrorMsg"] = GbkToUtf8::convert(pRspInfo->ErrorMsg);
            }

            // 发送数据给客户端
            m_tcp_server->broadcast(instrument_data.dump());
            Logger::info("合约数据发送成功: " + instrument_data.dump());
        } catch (const std::exception& e) {
            Logger::error("发送合约数据时发生错误: " + std::string(e.what()));
        }
    }
    else {
        Logger::error("m_tcp_server为nullptr");
    }
}

// 报单通知
void CTraderHandler::OnRtnOrder(CThostFtdcOrderField *pOrder)
{
    /////////////////////////////////////////////////////////////////////////
    // ///TFtdcOrderStatusType是一个报单状态类型
    // /////////////////////////////////////////////////////////////////////////
    // ///全部成交
    // #define THOST_FTDC_OST_AllTraded '0'
    // ///部分成交还在队列中
    // #define THOST_FTDC_OST_PartTradedQueueing '1'
    // ///部分成交不在队列中
    // #define THOST_FTDC_OST_PartTradedNotQueueing '2'
    // ///未成交还在队列中
    // #define THOST_FTDC_OST_NoTradeQueueing '3'
    // ///未成交不在队列中
    // #define THOST_FTDC_OST_NoTradeNotQueueing '4'
    // ///撤单
    // #define THOST_FTDC_OST_Canceled '5'
    // ///未知
    // #define THOST_FTDC_OST_Unknown 'a'
    // ///尚未触发
    // #define THOST_FTDC_OST_NotTouched 'b'
    // ///已触发
    // #define THOST_FTDC_OST_Touched 'c'

    // typedef char TThostFtdcOrderStatusType;
    if(m_tcp_server != nullptr) {
        try {
            json order_data;
            order_data["type"] = "order_data";
            
            if (pOrder == nullptr) {
                order_data["data"] = nullptr;
            } else {
                order_data["data"]["BrokerID"] = pOrder->BrokerID;
                order_data["data"]["InvestorID"] = pOrder->InvestorID;
                order_data["data"]["InstrumentID"] = pOrder->InstrumentID;
                order_data["data"]["OrderRef"] = pOrder->OrderRef;
                order_data["data"]["UserID"] = pOrder->UserID;
                order_data["data"]["OrderPriceType"] = std::string(1, pOrder->OrderPriceType);
                order_data["data"]["Direction"] = std::string(1, pOrder->Direction);
                order_data["data"]["CombOffsetFlag"] = pOrder->CombOffsetFlag;
                order_data["data"]["CombHedgeFlag"] = pOrder->CombHedgeFlag;
                order_data["data"]["LimitPrice"] = pOrder->LimitPrice;
                order_data["data"]["VolumeTotalOriginal"] = pOrder->VolumeTotalOriginal;
                order_data["data"]["TimeCondition"] = std::string(1, pOrder->TimeCondition);
                order_data["data"]["GTDDate"] = pOrder->GTDDate;
                order_data["data"]["VolumeCondition"] = std::string(1, pOrder->VolumeCondition);
                order_data["data"]["MinVolume"] = pOrder->MinVolume;
                order_data["data"]["ContingentCondition"] = std::string(1, pOrder->ContingentCondition);
                order_data["data"]["StopPrice"] = pOrder->StopPrice;
                order_data["data"]["ForceCloseReason"] = std::string(1, pOrder->ForceCloseReason);
                order_data["data"]["IsAutoSuspend"] = pOrder->IsAutoSuspend;
                order_data["data"]["BusinessUnit"] = pOrder->BusinessUnit;
                order_data["data"]["RequestID"] = pOrder->RequestID;
                order_data["data"]["OrderLocalID"] = pOrder->OrderLocalID;
                order_data["data"]["ExchangeID"] = pOrder->ExchangeID;
                order_data["data"]["ParticipantID"] = pOrder->ParticipantID;
                order_data["data"]["ClientID"] = pOrder->ClientID;
                order_data["data"]["ExchangeInstID"] = pOrder->ExchangeInstID;
                order_data["data"]["TraderID"] = pOrder->TraderID;
                order_data["data"]["InstallID"] = pOrder->InstallID;
                order_data["data"]["OrderSubmitStatus"] = std::string(1, pOrder->OrderSubmitStatus);
                order_data["data"]["NotifySequence"] = pOrder->NotifySequence;
                order_data["data"]["TradingDay"] = pOrder->TradingDay;
                order_data["data"]["SettlementID"] = pOrder->SettlementID;
                order_data["data"]["OrderSysID"] = pOrder->OrderSysID;
                order_data["data"]["OrderSource"] = std::string(1, pOrder->OrderSource);
                order_data["data"]["OrderStatus"] = std::string(1, pOrder->OrderStatus);
                order_data["data"]["OrderType"] = std::string(1, pOrder->OrderType);
                order_data["data"]["VolumeTraded"] = pOrder->VolumeTraded;
                order_data["data"]["VolumeTotal"] = pOrder->VolumeTotal;
                order_data["data"]["InsertDate"] = pOrder->InsertDate;
                order_data["data"]["InsertTime"] = pOrder->InsertTime;
                order_data["data"]["ActiveTime"] = pOrder->ActiveTime;
                order_data["data"]["SuspendTime"] = pOrder->SuspendTime;
                order_data["data"]["UpdateTime"] = pOrder->UpdateTime;
                order_data["data"]["CancelTime"] = pOrder->CancelTime;
                order_data["data"]["ActiveTraderID"] = pOrder->ActiveTraderID;
                order_data["data"]["ClearingPartID"] = pOrder->ClearingPartID;
                order_data["data"]["SequenceNo"] = pOrder->SequenceNo;
                order_data["data"]["FrontID"] = pOrder->FrontID;
                order_data["data"]["SessionID"] = pOrder->SessionID;
                order_data["data"]["UserProductInfo"] = pOrder->UserProductInfo;
                order_data["data"]["StatusMsg"] = GbkToUtf8::convert(pOrder->StatusMsg);
                order_data["data"]["UserForceClose"] = pOrder->UserForceClose;
                order_data["data"]["ActiveUserID"] = pOrder->ActiveUserID;
                order_data["data"]["BrokerOrderSeq"] = pOrder->BrokerOrderSeq;
                order_data["data"]["RelativeOrderSysID"] = pOrder->RelativeOrderSysID;
                order_data["data"]["ZCETotalTradedVolume"] = pOrder->ZCETotalTradedVolume;
                order_data["data"]["IsSwapOrder"] = pOrder->IsSwapOrder;
                order_data["data"]["BranchID"] = pOrder->BranchID;
                order_data["data"]["InvestUnitID"] = pOrder->InvestUnitID;
                order_data["data"]["AccountID"] = pOrder->AccountID;
                order_data["data"]["CurrencyID"] = pOrder->CurrencyID;
                order_data["data"]["IPAddress"] = pOrder->IPAddress;
                order_data["data"]["MacAddress"] = pOrder->MacAddress;
            }

            // 发送数据给客户端
            m_tcp_server->broadcast(order_data.dump());
            Logger::info("订单数据发送成功: " + order_data.dump());
        } catch (const std::exception& e) {
            Logger::error("发送订单数据时发生错误: " + std::string(e.what()));
        }
    }
    else {
        Logger::error("m_tcp_server为nullptr");
    }
}

// 成交通知
void CTraderHandler::OnRtnTrade(CThostFtdcTradeField *pTrade)
{
    if(m_tcp_server != nullptr) {
        try {
            json trade_data;
            trade_data["type"] = "trade_data";
            
            if (pTrade == nullptr) {
                trade_data["data"] = nullptr;
            } else {
                trade_data["data"]["BrokerID"] = pTrade->BrokerID;
                trade_data["data"]["InvestorID"] = pTrade->InvestorID;
                trade_data["data"]["InstrumentID"] = pTrade->InstrumentID;
                trade_data["data"]["OrderRef"] = pTrade->OrderRef;
                trade_data["data"]["UserID"] = pTrade->UserID;
                trade_data["data"]["ExchangeID"] = pTrade->ExchangeID;
                trade_data["data"]["TradeID"] = pTrade->TradeID;
                trade_data["data"]["Direction"] = std::string(1, pTrade->Direction);
                trade_data["data"]["OrderSysID"] = pTrade->OrderSysID;
                trade_data["data"]["ParticipantID"] = pTrade->ParticipantID;
                trade_data["data"]["ClientID"] = pTrade->ClientID;
                trade_data["data"]["TradingRole"] = std::string(1, pTrade->TradingRole);
                trade_data["data"]["ExchangeInstID"] = pTrade->ExchangeInstID;
                trade_data["data"]["OffsetFlag"] = std::string(1, pTrade->OffsetFlag);
                trade_data["data"]["HedgeFlag"] = std::string(1, pTrade->HedgeFlag);
                trade_data["data"]["Price"] = pTrade->Price;
                trade_data["data"]["Volume"] = pTrade->Volume;
                trade_data["data"]["TradeDate"] = pTrade->TradeDate;
                trade_data["data"]["TradeTime"] = pTrade->TradeTime;
                trade_data["data"]["TradeType"] = std::string(1, pTrade->TradeType);
                trade_data["data"]["PriceSource"] = std::string(1, pTrade->PriceSource);
                trade_data["data"]["TraderID"] = pTrade->TraderID;
                trade_data["data"]["OrderLocalID"] = pTrade->OrderLocalID;
                trade_data["data"]["ClearingPartID"] = pTrade->ClearingPartID;
                trade_data["data"]["BusinessUnit"] = pTrade->BusinessUnit;
                trade_data["data"]["SequenceNo"] = pTrade->SequenceNo;
                trade_data["data"]["TradingDay"] = pTrade->TradingDay;
                trade_data["data"]["SettlementID"] = pTrade->SettlementID;
                trade_data["data"]["BrokerOrderSeq"] = pTrade->BrokerOrderSeq;
                trade_data["data"]["TradeSource"] = std::string(1, pTrade->TradeSource);
                trade_data["data"]["InvestUnitID"] = pTrade->InvestUnitID;
            }

            // 发送数据给客户端
            m_tcp_server->broadcast(trade_data.dump());
            Logger::info("成交数据发送成功: " + trade_data.dump());
        } catch (const std::exception& e) {
            Logger::error("发送成交数据时发生错误: " + std::string(e.what()));
        }
    }
    else {
        Logger::error("m_tcp_server为nullptr");
    }
}

// 报单录入请求响应
void CTraderHandler::OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    if(m_tcp_server != nullptr) {
        try {
            json order_insert_rsp;
            order_insert_rsp["type"] = "rep_order_insert_data";
            
            if (pInputOrder == nullptr) {
                order_insert_rsp["data"] = nullptr;
            } else {
                order_insert_rsp["data"]["BrokerID"] = pInputOrder->BrokerID;
                order_insert_rsp["data"]["InvestorID"] = pInputOrder->InvestorID;
                order_insert_rsp["data"]["InstrumentID"] = pInputOrder->InstrumentID;
                order_insert_rsp["data"]["OrderRef"] = pInputOrder->OrderRef;
                order_insert_rsp["data"]["UserID"] = pInputOrder->UserID;
                order_insert_rsp["data"]["OrderPriceType"] = std::string(1, pInputOrder->OrderPriceType);
                order_insert_rsp["data"]["Direction"] = std::string(1, pInputOrder->Direction);
                order_insert_rsp["data"]["CombOffsetFlag"] = pInputOrder->CombOffsetFlag;
                order_insert_rsp["data"]["CombHedgeFlag"] = pInputOrder->CombHedgeFlag;
                order_insert_rsp["data"]["LimitPrice"] = pInputOrder->LimitPrice;
                order_insert_rsp["data"]["VolumeTotalOriginal"] = pInputOrder->VolumeTotalOriginal;
                order_insert_rsp["data"]["TimeCondition"] = std::string(1, pInputOrder->TimeCondition);
                order_insert_rsp["data"]["GTDDate"] = pInputOrder->GTDDate;
                order_insert_rsp["data"]["VolumeCondition"] = std::string(1, pInputOrder->VolumeCondition);
                order_insert_rsp["data"]["MinVolume"] = pInputOrder->MinVolume;
                order_insert_rsp["data"]["ContingentCondition"] = std::string(1, pInputOrder->ContingentCondition);
                order_insert_rsp["data"]["StopPrice"] = pInputOrder->StopPrice;
                order_insert_rsp["data"]["ForceCloseReason"] = std::string(1, pInputOrder->ForceCloseReason);
                order_insert_rsp["data"]["IsAutoSuspend"] = pInputOrder->IsAutoSuspend;
                order_insert_rsp["data"]["BusinessUnit"] = pInputOrder->BusinessUnit;
                order_insert_rsp["data"]["RequestID"] = pInputOrder->RequestID;
                order_insert_rsp["data"]["UserForceClose"] = pInputOrder->UserForceClose;
                order_insert_rsp["data"]["IsSwapOrder"] = pInputOrder->IsSwapOrder;
                order_insert_rsp["data"]["ExchangeID"] = pInputOrder->ExchangeID;
                order_insert_rsp["data"]["InvestUnitID"] = pInputOrder->InvestUnitID;
                order_insert_rsp["data"]["AccountID"] = pInputOrder->AccountID;
                order_insert_rsp["data"]["CurrencyID"] = pInputOrder->CurrencyID;
                order_insert_rsp["data"]["ClientID"] = pInputOrder->ClientID;
                order_insert_rsp["data"]["IPAddress"] = pInputOrder->IPAddress;
                order_insert_rsp["data"]["MacAddress"] = pInputOrder->MacAddress;
            }
            
            order_insert_rsp["bIsLast"] = bIsLast;
            
            if (pRspInfo) {
                order_insert_rsp["error"]["ErrorID"] = pRspInfo->ErrorID;
                order_insert_rsp["error"]["ErrorMsg"] = GbkToUtf8::convert(pRspInfo->ErrorMsg);
            }

            // 发送数据给客户端
            m_tcp_server->broadcast(order_insert_rsp.dump());
            Logger::info("报单录入响应数据发送成功: " + order_insert_rsp.dump());
        } catch (const std::exception& e) {
            Logger::error("发送报单录入响应数据时发生错误: " + std::string(e.what()));
        }
    }
    else {
        Logger::error("m_tcp_server为nullptr");
    }
}

// 错误应答
void CTraderHandler::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    Logger::info("OnRspError");
}

void CTraderHandler::OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    // /////////////////////////////////////////////////////////////////////////
    // ///TFtdcPositionDateType是一个持仓日期类型
    // /////////////////////////////////////////////////////////////////////////
    // ///今日持仓
    // #define THOST_FTDC_PSD_Today '1'
    // ///历史持仓
    // #define THOST_FTDC_PSD_History '2'

    // typedef char TThostFtdcPositionDateType;
    if(m_tcp_server != nullptr) {
        try {
            json position_data;
            position_data["type"] = "position_data";
            
            if (pInvestorPosition == nullptr) {
                position_data["data"] = nullptr;
            } else {
                position_data["data"]["InstrumentID"] = pInvestorPosition->InstrumentID;
                position_data["data"]["BrokerID"] = pInvestorPosition->BrokerID;
                position_data["data"]["InvestorID"] = pInvestorPosition->InvestorID;
                position_data["data"]["PosiDirection"] = std::string(1, pInvestorPosition->PosiDirection);
                position_data["data"]["HedgeFlag"] = std::string(1, pInvestorPosition->HedgeFlag);
                position_data["data"]["PositionDate"] = std::string(1, pInvestorPosition->PositionDate);
                position_data["data"]["YdPosition"] = pInvestorPosition->YdPosition;
                position_data["data"]["Position"] = pInvestorPosition->Position;
                position_data["data"]["LongFrozen"] = pInvestorPosition->LongFrozen;
                position_data["data"]["ShortFrozen"] = pInvestorPosition->ShortFrozen;
                position_data["data"]["OpenVolume"] = pInvestorPosition->OpenVolume;
                position_data["data"]["CloseVolume"] = pInvestorPosition->CloseVolume;
                position_data["data"]["PositionCost"] = pInvestorPosition->PositionCost;
                position_data["data"]["PreMargin"] = pInvestorPosition->PreMargin;
                position_data["data"]["UseMargin"] = pInvestorPosition->UseMargin;
                position_data["data"]["FrozenMargin"] = pInvestorPosition->FrozenMargin;
                position_data["data"]["FrozenCash"] = pInvestorPosition->FrozenCash;
                position_data["data"]["FrozenCommission"] = pInvestorPosition->FrozenCommission;
                position_data["data"]["Commission"] = pInvestorPosition->Commission;
                position_data["data"]["CloseProfit"] = pInvestorPosition->CloseProfit;
                position_data["data"]["PositionProfit"] = pInvestorPosition->PositionProfit;
                position_data["data"]["PreSettlementPrice"] = pInvestorPosition->PreSettlementPrice;
                position_data["data"]["SettlementPrice"] = pInvestorPosition->SettlementPrice;
                position_data["data"]["TradingDay"] = pInvestorPosition->TradingDay;
                position_data["data"]["OpenCost"] = pInvestorPosition->OpenCost;
                position_data["data"]["TodayPosition"] = pInvestorPosition->TodayPosition;
            }
            
            position_data["bIsLast"] = bIsLast;
            
            if (pRspInfo) {
                position_data["error"]["ErrorID"] = pRspInfo->ErrorID;
                position_data["error"]["ErrorMsg"] = GbkToUtf8::convert(pRspInfo->ErrorMsg);
            }

            // 发送数据给客户端
            m_tcp_server->broadcast(position_data.dump());
            Logger::info("持仓数据发送成功: " + position_data.dump());
        } catch (const std::exception& e) {
            Logger::error("发送持仓数据时发生错误: " + std::string(e.what()));
        }
    }
    else {
        Logger::error("m_tcp_server为nullptr");
    }
}

void CTraderHandler::OnRspQryOrder(CThostFtdcOrderField *pOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    if(m_tcp_server != nullptr) {
        try {
            json order_data;
            order_data["type"] = "qry_order_data";
            
            if (pOrder == nullptr) {
                order_data["data"] = nullptr;
            } else {
                order_data["data"]["BrokerID"] = pOrder->BrokerID;
                order_data["data"]["InvestorID"] = pOrder->InvestorID;
                order_data["data"]["InstrumentID"] = pOrder->InstrumentID;
                order_data["data"]["OrderRef"] = pOrder->OrderRef;
                order_data["data"]["UserID"] = pOrder->UserID;
                order_data["data"]["OrderPriceType"] = std::string(1, pOrder->OrderPriceType);
                order_data["data"]["Direction"] = std::string(1, pOrder->Direction);
                order_data["data"]["CombOffsetFlag"] = pOrder->CombOffsetFlag;
                order_data["data"]["CombHedgeFlag"] = pOrder->CombHedgeFlag;
                order_data["data"]["LimitPrice"] = pOrder->LimitPrice;
                order_data["data"]["VolumeTotalOriginal"] = pOrder->VolumeTotalOriginal;
                order_data["data"]["TimeCondition"] = std::string(1, pOrder->TimeCondition);
                order_data["data"]["GTDDate"] = pOrder->GTDDate;
                order_data["data"]["VolumeCondition"] = std::string(1, pOrder->VolumeCondition);
                order_data["data"]["MinVolume"] = pOrder->MinVolume;
                order_data["data"]["ContingentCondition"] = std::string(1, pOrder->ContingentCondition);
                order_data["data"]["StopPrice"] = pOrder->StopPrice;
                order_data["data"]["ForceCloseReason"] = std::string(1, pOrder->ForceCloseReason);
                order_data["data"]["IsAutoSuspend"] = pOrder->IsAutoSuspend;
                order_data["data"]["BusinessUnit"] = pOrder->BusinessUnit;
                order_data["data"]["RequestID"] = pOrder->RequestID;
                order_data["data"]["OrderLocalID"] = pOrder->OrderLocalID;
                order_data["data"]["ExchangeID"] = pOrder->ExchangeID;
                order_data["data"]["ParticipantID"] = pOrder->ParticipantID;
                order_data["data"]["ClientID"] = pOrder->ClientID;
                order_data["data"]["ExchangeInstID"] = pOrder->ExchangeInstID;
                order_data["data"]["TraderID"] = pOrder->TraderID;
                order_data["data"]["InstallID"] = pOrder->InstallID;
                order_data["data"]["OrderSubmitStatus"] = std::string(1, pOrder->OrderSubmitStatus);
                order_data["data"]["NotifySequence"] = pOrder->NotifySequence;
                order_data["data"]["TradingDay"] = pOrder->TradingDay;
                order_data["data"]["SettlementID"] = pOrder->SettlementID;
                order_data["data"]["OrderSysID"] = pOrder->OrderSysID;
                order_data["data"]["OrderSource"] = std::string(1, pOrder->OrderSource);
                order_data["data"]["OrderStatus"] = std::string(1, pOrder->OrderStatus);
                order_data["data"]["OrderType"] = std::string(1, pOrder->OrderType);
                order_data["data"]["VolumeTraded"] = pOrder->VolumeTraded;
                order_data["data"]["VolumeTotal"] = pOrder->VolumeTotal;
                order_data["data"]["InsertDate"] = pOrder->InsertDate;
                order_data["data"]["InsertTime"] = pOrder->InsertTime;
                order_data["data"]["ActiveTime"] = pOrder->ActiveTime;
                order_data["data"]["SuspendTime"] = pOrder->SuspendTime;
                order_data["data"]["UpdateTime"] = pOrder->UpdateTime;
                order_data["data"]["CancelTime"] = pOrder->CancelTime;
                order_data["data"]["ActiveTraderID"] = pOrder->ActiveTraderID;
                order_data["data"]["ClearingPartID"] = pOrder->ClearingPartID;
                order_data["data"]["SequenceNo"] = pOrder->SequenceNo;
                order_data["data"]["FrontID"] = pOrder->FrontID;
                order_data["data"]["SessionID"] = pOrder->SessionID;
                order_data["data"]["UserProductInfo"] = pOrder->UserProductInfo;
                order_data["data"]["StatusMsg"] = GbkToUtf8::convert(pOrder->StatusMsg);
                order_data["data"]["UserForceClose"] = pOrder->UserForceClose;
                order_data["data"]["ActiveUserID"] = pOrder->ActiveUserID;
                order_data["data"]["BrokerOrderSeq"] = pOrder->BrokerOrderSeq;
                order_data["data"]["RelativeOrderSysID"] = pOrder->RelativeOrderSysID;
                order_data["data"]["ZCETotalTradedVolume"] = pOrder->ZCETotalTradedVolume;
                order_data["data"]["IsSwapOrder"] = pOrder->IsSwapOrder;
                order_data["data"]["BranchID"] = pOrder->BranchID;
                order_data["data"]["InvestUnitID"] = pOrder->InvestUnitID;
                order_data["data"]["AccountID"] = pOrder->AccountID;
                order_data["data"]["CurrencyID"] = pOrder->CurrencyID;
                order_data["data"]["IPAddress"] = pOrder->IPAddress;
                order_data["data"]["MacAddress"] = pOrder->MacAddress;
            }
            
            order_data["bIsLast"] = bIsLast;
            
            if (pRspInfo) {
                order_data["error"]["ErrorID"] = pRspInfo->ErrorID;
                order_data["error"]["ErrorMsg"] = GbkToUtf8::convert(pRspInfo->ErrorMsg);
            }

            // 发送数据给客户端
            m_tcp_server->broadcast(order_data.dump());
            Logger::info("查询订单数据发送成功: " + order_data.dump());
        } catch (const std::exception& e) {
            Logger::error("发送查询订单数据时发生错误: " + std::string(e.what()));
        }
    }
    else {
        Logger::error("m_tcp_server为nullptr");
    }
}

void CTraderHandler::OnRspQryTrade(CThostFtdcTradeField *pTrade, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    if(m_tcp_server != nullptr) {
        try {
            json trade_data;
            trade_data["type"] = "qry_trade_data";
            
            if (pTrade == nullptr) {
                trade_data["data"] = nullptr;
            } else {
                trade_data["data"]["BrokerID"] = pTrade->BrokerID;
                Logger::info("BrokerID: " + trade_data["data"]["BrokerID"].get<std::string>());
                trade_data["data"]["InvestorID"] = pTrade->InvestorID;
                Logger::info("InvestorID: " + trade_data["data"]["InvestorID"].get<std::string>());
                trade_data["data"]["InstrumentID"] = pTrade->InstrumentID;
                Logger::info("InstrumentID: " + trade_data["data"]["InstrumentID"].get<std::string>());
                trade_data["data"]["OrderRef"] = pTrade->OrderRef;
                Logger::info("OrderRef: " + trade_data["data"]["OrderRef"].get<std::string>());
                trade_data["data"]["UserID"] = pTrade->UserID;
                Logger::info("UserID: " + trade_data["data"]["UserID"].get<std::string>());
                trade_data["data"]["ExchangeID"] = pTrade->ExchangeID;
                Logger::info("ExchangeID: " + trade_data["data"]["ExchangeID"].get<std::string>());
                trade_data["data"]["TradeID"] = pTrade->TradeID;
                Logger::info("TradeID: " + trade_data["data"]["TradeID"].get<std::string>());
                trade_data["data"]["Direction"] = std::string(1, pTrade->Direction);
                Logger::info("Direction: " + trade_data["data"]["Direction"].get<std::string>());
                trade_data["data"]["OrderSysID"] = pTrade->OrderSysID;
                Logger::info("OrderSysID: " + trade_data["data"]["OrderSysID"].get<std::string>());
                trade_data["data"]["ParticipantID"] = pTrade->ParticipantID;
                Logger::info("ParticipantID: " + trade_data["data"]["ParticipantID"].get<std::string>());
                trade_data["data"]["ClientID"] = pTrade->ClientID;
                // trade_data["data"]["TradingRole"] = std::string(1, pTrade->TradingRole);
                // Logger::info("TradingRole: " + trade_data["data"]["TradingRole"].get<std::string>());
                trade_data["data"]["ExchangeInstID"] = pTrade->ExchangeInstID;
                Logger::info("ExchangeInstID: " + trade_data["data"]["ExchangeInstID"].get<std::string>());
                trade_data["data"]["OffsetFlag"] = std::string(1, pTrade->OffsetFlag);
                Logger::info("OffsetFlag: " + trade_data["data"]["OffsetFlag"].get<std::string>());
                trade_data["data"]["HedgeFlag"] = std::string(1, pTrade->HedgeFlag);
                Logger::info("HedgeFlag: " + trade_data["data"]["HedgeFlag"].get<std::string>());
                trade_data["data"]["Price"] = std::to_string(pTrade->Price);
                Logger::info("Price: " + std::to_string(pTrade->Price));
                trade_data["data"]["Volume"] = std::to_string(pTrade->Volume);
                Logger::info("Volume: " + std::to_string(pTrade->Volume));
                trade_data["data"]["TradeDate"] = pTrade->TradeDate;
                Logger::info("TradeDate: " + trade_data["data"]["TradeDate"].get<std::string>());
                trade_data["data"]["TradeTime"] = pTrade->TradeTime;
                Logger::info("TradeTime: " + trade_data["data"]["TradeTime"].get<std::string>());
                trade_data["data"]["TradeType"] = std::string(1, pTrade->TradeType);
                Logger::info("TradeType: " + trade_data["data"]["TradeType"].get<std::string>());
                trade_data["data"]["PriceSource"] = std::string(1, pTrade->PriceSource);
                Logger::info("PriceSource: " + trade_data["data"]["PriceSource"].get<std::string>());
                trade_data["data"]["TraderID"] = pTrade->TraderID;
                Logger::info("TraderID: " + trade_data["data"]["TraderID"].get<std::string>());
                trade_data["data"]["OrderLocalID"] = pTrade->OrderLocalID;
                Logger::info("OrderLocalID: " + trade_data["data"]["OrderLocalID"].get<std::string>());
                trade_data["data"]["ClearingPartID"] = pTrade->ClearingPartID;
                Logger::info("ClearingPartID: " + trade_data["data"]["ClearingPartID"].get<std::string>());
                // trade_data["data"]["BusinessUnit"] = pTrade->BusinessUnit;
                // Logger::info("BusinessUnit: " + trade_data["data"]["BusinessUnit"].get<std::string>());
                // trade_data["data"]["SequenceNo"] = pTrade->SequenceNo;
                // Logger::info("SequenceNo: " + trade_data["data"]["SequenceNo"].get<std::string>());
                trade_data["data"]["TradingDay"] = std::string(pTrade->TradingDay);
                Logger::info("TradingDay: " + trade_data["data"]["TradingDay"].get<std::string>());
                // trade_data["data"]["SettlementID"] = std::string(pTrade->SettlementID);
                // Logger::info("SettlementID: " + trade_data["data"]["SettlementID"].get<std::string>());
                // trade_data["data"]["BrokerOrderSeq"] = std::string(pTrade->BrokerOrderSeq);
                // Logger::info("BrokerOrderSeq: " + trade_data["data"]["BrokerOrderSeq"].get<std::string>());
                // trade_data["data"]["TradeSource"] = std::string(1, pTrade->TradeSource);
                // Logger::info("TradeSource: " + trade_data["data"]["TradeSource"].get<std::string>());
                trade_data["data"]["InvestUnitID"] = std::string(pTrade->InvestUnitID);
                Logger::info("InvestUnitID: " + trade_data["data"]["InvestUnitID"].get<std::string>());
            }
            
            trade_data["bIsLast"] = bIsLast;
            
            if (pRspInfo) {
                trade_data["error"]["ErrorID"] = std::to_string(pRspInfo->ErrorID);
                Logger::info("ErrorID: " + trade_data["error"]["ErrorID"].get<std::string>());
                trade_data["error"]["ErrorMsg"] = GbkToUtf8::convert(pRspInfo->ErrorMsg);
                Logger::info("ErrorMsg: " + trade_data["error"]["ErrorMsg"].get<std::string>());
            }
            // 发送数据给客户端
            m_tcp_server->broadcast(trade_data.dump());
            Logger::info("查询成交数据发送成功: " + trade_data.dump());
        } catch (const std::exception& e) {
            Logger::error("发送查询成交数据时发生错误: " + std::string(e.what()));
        }
    }
    else {
        Logger::error("m_tcp_server为nullptr");
    }
}

void CTraderHandler::OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    if(m_tcp_server != nullptr) {
        try {
            json account_data;
            account_data["type"] = "account_data";
            
            if (pTradingAccount == nullptr) {
                account_data["data"] = nullptr;
            } else {
                account_data["data"]["BrokerID"] = pTradingAccount->BrokerID;
                account_data["data"]["AccountID"] = pTradingAccount->AccountID;
                account_data["data"]["PreMortgage"] = pTradingAccount->PreMortgage;
                account_data["data"]["PreCredit"] = pTradingAccount->PreCredit;
                account_data["data"]["PreDeposit"] = pTradingAccount->PreDeposit;
                account_data["data"]["PreBalance"] = pTradingAccount->PreBalance;
                account_data["data"]["PreMargin"] = pTradingAccount->PreMargin;
                account_data["data"]["InterestBase"] = pTradingAccount->InterestBase;
                account_data["data"]["Interest"] = pTradingAccount->Interest;
                account_data["data"]["Deposit"] = pTradingAccount->Deposit;
                account_data["data"]["Withdraw"] = pTradingAccount->Withdraw;
                account_data["data"]["FrozenMargin"] = pTradingAccount->FrozenMargin;
                account_data["data"]["FrozenCash"] = pTradingAccount->FrozenCash;
                account_data["data"]["FrozenCommission"] = pTradingAccount->FrozenCommission;
                account_data["data"]["CurrMargin"] = pTradingAccount->CurrMargin;
                account_data["data"]["CashIn"] = pTradingAccount->CashIn;
                account_data["data"]["Commission"] = pTradingAccount->Commission;
                account_data["data"]["CloseProfit"] = pTradingAccount->CloseProfit;
                account_data["data"]["PositionProfit"] = pTradingAccount->PositionProfit;
                account_data["data"]["Balance"] = pTradingAccount->Balance;
                account_data["data"]["Available"] = pTradingAccount->Available;
                account_data["data"]["WithdrawQuota"] = pTradingAccount->WithdrawQuota;
                account_data["data"]["Reserve"] = pTradingAccount->Reserve;
                account_data["data"]["TradingDay"] = pTradingAccount->TradingDay;
                account_data["data"]["SettlementID"] = pTradingAccount->SettlementID;
                account_data["data"]["Credit"] = pTradingAccount->Credit;
                account_data["data"]["Mortgage"] = pTradingAccount->Mortgage;
                account_data["data"]["ExchangeMargin"] = pTradingAccount->ExchangeMargin;
                account_data["data"]["DeliveryMargin"] = pTradingAccount->DeliveryMargin;
                account_data["data"]["ExchangeDeliveryMargin"] = pTradingAccount->ExchangeDeliveryMargin;
                account_data["data"]["ReserveBalance"] = pTradingAccount->ReserveBalance;
                account_data["data"]["CurrencyID"] = pTradingAccount->CurrencyID;
            }
            
            account_data["bIsLast"] = bIsLast;
            
            if (pRspInfo) {
                account_data["error"]["ErrorID"] = pRspInfo->ErrorID;
                account_data["error"]["ErrorMsg"] = GbkToUtf8::convert(pRspInfo->ErrorMsg);
            }

            // 发送数据给客户端
            m_tcp_server->broadcast(account_data.dump());
            Logger::info("账户数据发送成功: " + account_data.dump());
        } catch (const std::exception& e) {
            Logger::error("发送账户数据时发生错误: " + std::string(e.what()));
        }
    }
    else {
        Logger::error("m_tcp_server为nullptr");
    }
}

void CTraderHandler::setServer(TcpServer* server) {
    m_tcp_server = server;
}

void CTraderHandler::ReqAuthenticate()
{
    CThostFtdcReqAuthenticateField field;
    memset(&field, 0, sizeof(field));
    strcpy(field.BrokerID, m_brokerID.c_str());
    strcpy(field.UserID, m_userID.c_str());
    strcpy(field.AppID, m_app_id.c_str());
    strcpy(field.AuthCode, m_auth_code.c_str());
    m_ptraderapi->ReqAuthenticate(&field, 5);
}

void CTraderHandler::OnRspAuthenticate(CThostFtdcRspAuthenticateField *pRspAuthenticateField, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)
{
    Logger::info("OnRspAuthenticate\n");
    if (pRspInfo != NULL && pRspInfo->ErrorID == 0)
    {
        Logger::info("认证成功");
        login();
    }
    else
    {
        Logger::error("认证失败，ErrorID=" + std::to_string(pRspInfo->ErrorID) + "  ,ErrMsg=" + GbkToUtf8::convert(pRspInfo->ErrorMsg));
    }
}

